<?php
class PublicAction extends BaseAction
{
    public function index()
    {
    }

    /**
     * 显示登录界面
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function login()
    {
        $isAjax = $this->isAjax();
        if ($this->isPost()) {
            $this->autoCheckToken();
            //登录执行判断
            $email = $this->_post('email');
            $pwd = '';
            if ($isAjax) {
                $pwd = $this->_post('pwd');
            } else {
                $pwd = md5($this->_post('pwd'));
            }
            $user = $this->checkLogin($email, $pwd);
            $uid = $user['id'];
            if ($user) {
                $rem = intval($this->_post('rem'));
                //记录用户名
                if ($rem) {
                    $cookieName = 'user_login_email';
                    $userLoginEmail = Cookie::get($cookieName);
                    if (empty($userLoginEmail)) {
                        Cookie::set($cookieName, $email);
                    } else {
                        if ($userLoginEmail != $email) {
                            Cookie::set($cookieName, $email);
                        }
                    }
                } else {
                    //不选择记住用户名就删除记录信息
                    $cookieName = 'user_login_email';
                    Cookie::delete($cookieName);
                }
                $this->checkUserStatus($user['status'], $user['email']);
                $this->logUserLogin($user);
                setLoginUserInfo($uid);
                //注册成功修改，在线状态。
                setOnline($uid);
                //记录登陆日志
                loginLog($uid);
                //记录登陆次数
                addUserLoginCount($uid);
                //进行登陆积分处理
                if ($user['status'] == 2) {
                    D('CreditUser')->change($uid, 1); //执行登陆积分操作
                }
                if ($isAjax) {
                    $this->ajaxReturn(L('_USER_LOGIN_SUCCESS_'), null, 1);
                } else {
                    $this->assign('jumpUrl', SITE_URL);
                    $this->successLang('_USER_LOGIN_SUCCESS_');
                }
            } else {
                //进行登录失败分析
                $user = $this->checkLogin($email);
                $errorStr = "";
                if ($user) {
                    $errorStr = L('_LOGIN_PASSWORD_ERROR_');
                } else {
                    $errorStr = L('_LOGIN_EMAIL_ERROR_');
                }
                if ($isAjax) {
                    $this->ajaxReturn($errorStr, null, 0);
                } else {
                    $this->error($errorStr);
                }
            }
        } else {
            //如果已经登录调整到个人首页
            if (!$isAjax) {
                $this->display();
            } else {
                //获取记住帐号
                $cookieName = 'user_login_email';
                $userLoginEmail = Cookie::get($cookieName);
                if (!empty($userLoginEmail)) {
                    $this->assign('email', $userLoginEmail);
                }
                $this->ajaxReturn($this->fetch('Public:loginBigBox'), null, 1);
            }
        }
    }

    /**
     * 执行登出操作
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function loginOut()
    {
        if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION);
            session_destroy();
            $this->assign('userInfo', null);
            $this->assign('userScore', null);
            $this->assign('uid', null);
            $this->assign('jumpUrl', SITE_URL);
            $this->successLang('_LOGIN_OUT_SUCCESS_');
        }
    }

    /**
     * 用户注册
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function register()
    {
        //TODO 安全性提高
        $uid = getLoginUserInfo();
        if ($uid) {
            $this->error('你已经是注册用户，不能在注册啦！');
        }
        $ruid = intval($this->_get('uid'));
        if ($ruid) {
            $user = M('Users')->find($ruid);
            if ($user) {
                $this->assign('user', $user);
            } else {
                $this->error('邀请用户信息不存在！');
            }
        }
        if ($this->isPost()) {
            $email = $this->_post('email');
            if ($this->regex($email, 'email')) {
                $data['email'] = $email;
                $data['uid'] = intval($this->_post('uid'));//记录邀请人
                $this->sendSignupMail($data);
                $this->display('sendMail');
                exit;
            } else {
                $this->errorLang('_WRITE_EXACTNESS_EMAIL_');
            }
        }
        $this->display();
    }

    /**
     * 激活邮件
     */
    public function activation()
    {
        $RegisterMailModel = M('RegisterMail');
        $map['key'] = trim($this->_get('key'));
        $registerMail = $RegisterMailModel->where($map)->find();
        if ($registerMail) {
            if ($registerMail['status'] == 2) {
                $this->errorLang('_EMAIL_PASS_AUTH_');
            }
        } else {
            $this->errorLang('_EMAIL_DATA_ERROR_');
        }
        if ($this->isPost()) {
            $data = $this->getRegisterData();
            $data['email'] = $registerMail['email'];
            $UsersModel = D('Users');
            if ($UsersModel->getCountByName($data['name'])) {
                $this->error('此昵称已经被人使用！');
            }
            $data = $UsersModel->create($data); //验证
            $rs = false;
            if ($data) {
                $rs = $UsersModel->add($data); //添加
                if ($rs) {
                    //执行登录状态
                    $user['id'] = $rs;
                    //注册成功，进行授权
                    $sql = 'REPLACE INTO ' . C('DB_PREFIX') . 'role_user (role_id,user_id) VALUES (2,' . $user['id'] . ')';
                    M('')->query($sql);
                    //执行登陆处理
                    //实现登陆 和 跳转
                    setLoginUserInfo($user['id']);
                    //注册成功修改，在线状态。
                    setOnline($user['id']);
                    //记录登陆次数
                    addUserLoginCount($user['id']);
                    //
                    loginLog($user['id']);
                    //用户邀请判断
                    if ($registerMail['uid']) {
                        $this->checkInvite($registerMail['uid'], $rs);
                    }
                    $this->assign('jumpUrl', SITE_URL);
                    $this->successLang('_ACCOUNT_ACTION_SUCCESS_');
                } else {
                    $this->errorLang('_REGISTRATION_FAILED_');
                }
            } else {
                $this->error($UsersModel->getError());
            }
        }
        $this->assign('m', $registerMail);
        $this->display();
    }

    /**
     * 忘记密码
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function forgotPassword()
    {
        //判断是注册用户 并且是可用账号
        //判断是否有找回信息 密码 一天内只允许找回一次
        //符合条件发送邮件，如数据库中操作信息修改不存在添加
        if ($this->isPost()) {
            $this->autoCheckToken();
            $email = $this->_post('email');
            if ($this->regex($email, 'email')) {
                $UsersModel = D('Users');
                $user = $UsersModel->getOneByEmail($email);
                if ($user) {
                    $ForgotPasswordModel = D('ForgotPassword');
                    $fp = $ForgotPasswordModel->getOneByEmail($email);
                    $key = md5(time()) . encrypt($user['email']);

                    $data = array();
                    $rs = false;
                    $users = array();
                    $body = array();

                    $data['key'] = $key;
                    $data['status'] = 1;
                    $data['uid'] = $user['id'];
                    $users[$user['name']] = $email; //收件人
                    $body['keyUrl'] = SITE_URL . '/getpasswd/' . $key; //激活地址
                    $isSend = $this->sendMail($users, null, $body, 'getpasswd');
                    if ($isSend) {
                        $data['last_update'] = time();
                        $data['update_ip'] = get_client_ip();
                        if ($fp) {
                            //判断时间限制
                            if ($fp['last_update'] > (time() - 600 * 5)) {
                                $this->errorLang('_WAIT_MINUTES_SEND_');
                            }
                            //执行修改
                            $rs = $ForgotPasswordModel->save($data);
                        } else {
                            //执行添加
                            $data['email'] = $user['email'];
                            $data['create_time'] = time();
                            $data['create_ip'] = get_client_ip();
                            $rs = $ForgotPasswordModel->add($data);
                        }
                        if ($rs) {
                            $this->assign('waitSecond', 5);
                            $this->assign('jumpUrl', SITE_URL);
                            $this->successLang('_FORGOT_PASSWORD_MAIL_SEND_SUCCESS_');
                        } else {
                            $this->successLang('_DATA_RECORD_FAILS_');
                        }
                    } else {
                        $this->errorLang('_SEND_EMAIL_ERROR_');
                    }
                } else {
                    $this->errorLang('_EMAIL_DATA_ERROR_');
                }
            } else {
                $this->errorLang('_EMAIL_FORMAT_ERROR_');
            }
        } else {
            $this->display();
        }
    }

    /**
     * 密码找回 修改密码
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function passwdChange()
    {
        $key = $this->_get('key');
        if ($key) {
            $ForgotPasswordModel = D('ForgotPassword');
            $fp = $ForgotPasswordModel->getOneByKey($key);
            if ($fp) {
                //判断时间限制
                if ($fp['last_update'] < (time() - 600 * 60 * 24)) {
                    $this->errorLang('_FORGOT_PASSWORD_KEY_FAIL_');
                }
                if ($fp['status'] == 1) {

                } else {
                    $this->error('亲，你已经使用过啦，现在不可用啦！');
                }
                if ($this->isPost()) {
                    $this->autoCheckToken();
                    //设置数据
                    $this->passwdModify($fp['uid'], $key);
                }
            } else {
                $this->errorLang('_FORGOT_PASSWORD_KEY_NO_');
            }
            $this->assign('fp', $fp);
            $this->display();
        }
    }

    /**
     * 执行密码修改
     * @param  $key
     * @author Ice <iceinto@mallog.com.cn>
     */
    private function passwdModify($uid, $key)
    {
        $pwd = $this->_post('pwd');
        $repwd = $this->_post('repwd');
        if ($pwd && $repwd && ($pwd == $repwd)) {
            $UsersModel = M('Users');
            //执行密码修改
            $data = array();
            $data['id'] = $uid;
            $data['pwd'] = md5($pwd);
            $rs = $UsersModel->save($data);
            if ($rs) {
                //修改找回密码状态
                unset($data);
                $newTime = time();
                $ip = get_client_ip();
                $data['last_update'] = $newTime;
                $data['update_ip'] = $ip;
                $data['activation_time'] = $newTime;
                $data['activation_ip'] = $ip;
                $data['uid'] = $uid;
                $data['status'] = 0;
                M('ForgotPassword')->save($data);
                $this->assign('waitSecond', 5);
                $this->assign('jumpUrl', SITE_URL . '/login');
                //去除当前登陆信息
                $this->successLang('_PASSWORD_SUCCESSFULLY_CHANGED_');
            } else {
                $this->errorLang('_PASSWORD_CHANGED_FAILED_');
            }
        } else {
            $this->errorLang('_TWO_PASSWORD_DIFFERENT_');
        }
    }

    /**
     * 获取验证码
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function verify()
    {
        Image::buildImageVerify(4, 1, 'png', 48, 28);
    }

    /**
     * 获取默认邮箱地址
     * @param string $email
     * @author Ice <iceinto@mallog.com.cn>
     */
    private function emailGetUrl($email)
    {
        $rs = false;
        $str = explode("@", $email);
        $strCount = count($str);
        if ($strCount > 1) {
            $strYm = explode(".", $str[$strCount - 1]);
            $strYmCount = count($strYm);
            if ($strYmCount == 2) {
                return 'http://mail.' . $strYm[0] . '.' . $strYm[1];
            }
        }
        return $rs;
    }

    /**
     * 获取注册数据
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function getRegisterData()
    {
        $data = array();
        $birthday = null;
        $data['status'] = 1;
        $data['name'] = $this->_post('name');
        $data['pwd'] = $this->_post('pwd');
        $data['repwd'] = $this->_post('repwd');
        if (!empty($data['repwd'])) {
            if ($data['pwd'] != $data['repwd']) {
                $this->errorLang('_TWO_PASSWORD_DIFFERENT_');
            }
            unset($data['repwd']);
        } else {
            $this->errorLang('_TWO_PASSWORD_MUST_');
        }
        $data['sex'] = intval($this->_post('sex'));
        if ($data['sex'] == 1 || $data['sex'] == 2) {
        } else {
            $this->errorLang('_SEX_SELECTION_ERROR_');
        }
        if (!$data['name']) {
            $this->errorLang('_NAME_MUST_');
        }
        //重整出生年月
        $year = intval($this->_post('year'));
        $month = intval($this->_post('month'));
        $day = intval($this->_post('day'));
        if ($year && $month && $day) {
            $birthday = $year . '-' . $month . '-' . $day;
        } else {
            $this->errorLang('_BIRTHDAY_MUST_');
        }
        $data['birthday'] = strtotime($birthday);
        if ($data['birthday'] > time()) {
            $this->errorLang('_BIRTHDAY_TIME_ERROR_');
        } else if ($data['birthday'] < time() - (60 * 60 * 24 * 365 * 120)) {
            $this->errorLang('_AGE_ERROR_');
        }
        return $data;
    }

    /**
     * 注册邮件发送 可进行初次发送和重复发送
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function sendSignupMail($data)
    {
        $title = array();
        $body = array();
        $map = array();
        $RegisterMailModel = D('RegisterMail');
        $UsersModel = D('Users');

        $map['email'] = $data['email'];
        $rs = $UsersModel->where($map)->count();
        if ($rs) {
            $this->error('此邮箱已经被注册过！请换个邮箱！');
        }
        //查看是否已经发送过
        $registerMail = $RegisterMailModel->where($map)->find();
        $oTime = time() - 600 * 5; //过期时间控制
        if ($registerMail) {
            if ($registerMail['status'] == 2) {
                $this->errorLang('_EMAIL_PASS_AUTH_');
            } else if ($oTime < $registerMail['update_time']) {
                $this->errorLang('_WAIT_MINUTES_SEND_');
            } else if ($registerMail['status'] == 1) {
                //执行重新发送
                $users[$registerMail['email']] = $registerMail['email'];
                $body['email'] = $registerMail['email'];
                $body['activation_url'] = SITE_URL . U('/activation/' . $registerMail['key']);
                $rs = $this->sendMail($users, $title, $body, 'register');
                if ($rs) {
                    $this->assign('email', $registerMail['email']);
                    $this->assign('email_url', $this->emailGetUrl($registerMail['email']));
                    //更新发送时间
                } else {
                    $this->errorLang('_SEND_REGISTER_EMAIL_ERROR_');
                }
            } else {
                $this->error('验证邮件状态不对！');
            }
        } else {
            //查询邮件有没有发送过
            $users[$data['email']] = $data['email'];
            $encrypt = encrypt($data['email']); //生成加密文
            $body['email'] = $data['email'];
            $body['activation_url'] = SITE_URL . U('/activation/' . $encrypt);
            $rs = $this->sendMail($users, $title, $body, 'register');
            if ($rs) {
                $rs = $RegisterMailModel->addRMail($data['email'], $encrypt, $data['uid']);
                if ($rs) {
                    $this->assign('email', $data['email']);
                    $this->assign('email_url', $this->emailGetUrl($data['email']));
                } else {
                    Log::write($data['email'] . '认证邮件发送成功！数据记录失败！');
                    $this->errorSendMail($data['email'] . '认证邮件发送成功！数据记录失败！ 请联系管理员！');
                }
            } else {
                Log::write($data['email'] . '认证邮件发送失败！');
                $this->errorSendMail('认证邮件发送失败！ 请联系管理员！');
            }
        }
    }

    /**
     * 修改最后登陆地址和IP
     * @param array $user
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function logUserLogin($user)
    {
        $data['id'] = $user['id'];
        $data['last_login_time'] = time();
        $data['last_login_ip'] = get_client_ip();
        M('Users')->save($data);
    }

    /**
     * 检查用户状态
     * @param int $status 状态
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function checkUserStatus($status, $email = null)
    {
        if ($status == 3) {
            $this->assign('waitSecond', 5);
            $this->assign('jumpUrl', emailGetUrl($email));
            $url = SITE_URL . '/register/';
            $this->error('你的账号需要邮件激活后，才能登陆网站！如果没有收到可以点击 <a href="' . $url . '">重发 </a>！');
        }
    }

    /**
     * 检查登录信息是否正确
     * @param String $email 用户登录邮箱
     * @param String $pas 用户密码
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function checkLogin($email, $pwd = null)
    {
        $user = array();
        $map = array();
        $UserModel = M('Users');
        $field = 'id,name,email,status';
        if ($email && $pwd) {
            $map['email'] = $email;
            $map['pwd'] = $pwd;
        } else if ($email) {
            $map['email'] = $email;
        } else {
            return false;
        }
        $user = $UserModel->where($map)->field($field)->find();
        if ($user) {
            return $user;
        }
        return false;
    }

    /**
     * 查看用户是否是被邀请
     * @param int $uid
     * @param int $id
     * @return void
     * @author Ice <iceinto@mallog.com.cn>
     */
    protected function checkInvite($uid, $id)
    {
        if ($uid) {
            $user = M('Users')->find($uid);
            if ($user) {
                //记录用户信息
                $data['uid'] = $uid;
                $data['invite_uid'] = $id;
                $data['create_time'] = time();
                M('InviteUser')->add($data);
            }
        }
    }
}

?>